package com.lt.lumentracks.mapper;

import com.lt.lumentracks.entity.po.ConversationUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 会话成员表 (关联表) Mapper 接口
 * </p>
 *
 * @author swl
 * @since 2025-10-06
 */
public interface ConversationUserMapper extends BaseMapper<ConversationUser> {


    /**
     * 批量更新会话成员表
     * @param cuList 会话成员表集合
     * @return true:更新成功，false:更新失败
     */
    boolean updateBatch(@Param("cuList") List<ConversationUser> cuList);

    /**
     * 判断单聊会话是否存在
     * @param senderId 发送者id
     * @param receiverId 接收者id
     * @return true:存在，false:不存在
     */
    @Select("SELECT count(*) FROM conversation_user cu1 " +
            "         JOIN conversation_user cu2 ON cu1.conversation_id = cu2.conversation_id  " + // 通过会话ID连接cu1和cu2
            "         JOIN conversation c ON c.id = cu1.conversation_id  " + // 将会话表与cu1（或cu2）关联
            "WHERE c.conversation_type = 1 AND " +
            "      ((cu1.user_id = #{senderId} AND cu2.user_id = #{receiverId}) " +
            "           OR " +
            "       (cu1.user_id = #{receiverId} AND cu2.user_id = #{senderId})) ")
    long isSingleChatExists(Integer senderId, Integer receiverId);


    /** 获取私聊会话
     * @param currentId 当前用户id
     * @param talkerUid 对方用户id
     * @return 私聊会话id
     */
    @Select("SELECT DISTINCT cu1.conversation_id " +
            "FROM conversation_user cu1 " +
            "   JOIN conversation_user cu2 ON cu1.conversation_id = cu2.conversation_id  " + // 通过会话ID连接cu1和cu2
            "   JOIN conversation c ON c.id = cu1.conversation_id  " + // 将会话表与cu1（或cu2）关联
            "WHERE c.conversation_type = 1 AND " +
            "      ((cu1.user_id = #{currentId} AND cu2.user_id = #{talkerUid}) " +
            "           OR " +
            "       (cu1.user_id = #{talkerUid} AND cu2.user_id = #{currentId})) ")
    List<Long> getSingleChat(Integer currentId, Integer talkerUid);


    /** 批量查询（对于当前用户来说的）每个会话的未读消息数
     * @param rawIds 会话id集合
     * @param userId 当前用户id
     * @param maxReturnCount 最大返回数量
     * @return 存储Map对象的List集合，其中key为会话ID，value为未读消息数
     */
    @MapKey("conv_id")
    List<Map<String, Object>> countUnreadMessages(List<Long> rawIds, Integer userId, int maxReturnCount);
}
